package com.youlai.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.global.EventHandler;
import com.youlai.system.model.entity.DeviceConfig;
import com.youlai.system.model.query.DeviceConfigQuery;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.service.DeviceConfigService;
import groovy.util.logging.Slf4j;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedDataItem;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Tag(name = "970.PLC Device")
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/device")
@Slf4j
public class DeviceConfigController {


    private final ExecutorService executor = Executors.newFixedThreadPool(50); // 创建一个固定大小的线程池

    private final ThreadPoolTaskExecutor taskExecutor;

    private final DeviceConfigService deviceConfigService;

    static ManagedDataItem.DataValueListener listener;

    @GetMapping("/page")
    @Operation(summary = "分页查询")
    public PageResult<DeviceConfig> getDeviceConfigPage(@ParameterObject DeviceConfigQuery DeviceConfigQuery){
        Page<DeviceConfig> result = deviceConfigService.getDeviceConfigPage(DeviceConfigQuery);
        return PageResult.success(result);
    }

    @GetMapping
    @Operation(summary = "获取所有")
    public Result<List<DeviceConfig>> getAllTrendConfig(){
        return  Result.success(deviceConfigService.list());
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取By Id")
    public Result<DeviceConfig> getAccountById(@PathVariable Long id){
        return Result.success(deviceConfigService.getById(id));
    }

    @PutMapping
    @Operation(summary = "更新信息")
    @PreAuthorize("@ss.hasPerm('sys:device:edit')")
    public Result<Boolean> updateAccount(@Valid  @RequestBody DeviceConfig DeviceConfig){
        return  Result.judge(deviceConfigService.updateById(DeviceConfig));
    }

    @DeleteMapping("/{ids}")
    @Operation(summary = "删除信息")
    @PreAuthorize("@ss.hasPerm('sys:device:delete')")
    public Result<Boolean> deleteAccount(@PathVariable String ids){
        return Result.judge(deviceConfigService.deleteDeviceConfig(ids));
    }

    @PostMapping
    @PreventDuplicateSubmit
    @Operation(summary = "添加")
    @PreAuthorize("@ss.hasPerm('sys:device:add')")
    public Result<Boolean> saveAccount(@Valid @RequestBody DeviceConfig DeviceConfig){
        return Result.judge(deviceConfigService.save(DeviceConfig));
    }

    @PostMapping("/list")
    @PreventDuplicateSubmit
    @Operation(summary = "批量添加")
    @PreAuthorize("@ss.hasPerm('sys:device:addList')")
    public Result<Boolean> saveTrendConfigList(@Valid @RequestBody List<DeviceConfig> deviceConfigList){
        boolean allSucceeded = deviceConfigList.stream()
                .allMatch(deviceConfig -> deviceConfigService.save(deviceConfig));
        return Result.judge(allSucceeded);
    }

    @PostMapping("/op/connect")
    @PreventDuplicateSubmit
    @Operation(summary = "连接PLC")
    @PreAuthorize("@ss.hasPerm('sys:op:connect')")
    public Result<Boolean> connect(@RequestBody Long id) throws Exception {
        return Result.judge(deviceConfigService.connectPlc(id));
    }

    @PostMapping("/op/disconnect")
    @PreventDuplicateSubmit
    @Operation(summary = "断开PLC")
    @PreAuthorize("@ss.hasPerm('sys:op:disconnect')")
    public Result<Boolean> disconnect(@RequestBody Long id)  {
        EventHandler.Add("断开PLC",
                EventHandler.Type.DEVICE,
                EventHandler.DeviceGroup.GROUP1,
                "现场设备",
                "S7-1500",
                EventHandler.MessageType.MESSAGE,
                "尝试断开连接PLC"
        );
        return Result.judge(deviceConfigService.disconnectPlc(id));
    }
    @PostMapping("/op/subscribe")
    @PreventDuplicateSubmit
    @Operation(summary = "开始订阅")
    @PreAuthorize("@ss.hasPerm('sys:op:subscribe')")
    public Result<Boolean> subscribe(@RequestBody Long id)  throws Exception    {
//        EventHandler.Add("订阅PLC",
//                EventHandler.Type.DEVICE,
//                EventHandler.DeviceGroup.GROUP1,
//                "现场设备",
//                "S7-1500",
//                EventHandler.MessageType.MESSAGE,
//                "开始订阅PLC节点"
//        );
        return Result.judge(deviceConfigService.subscribePlc(id));
    }

    @PostMapping("/op/cancel")
    @PreventDuplicateSubmit
    @Operation(summary = "取消订阅")
    @PreAuthorize("@ss.hasPerm('sys:op:cancel')")
    public Result<Boolean> cancel(@RequestBody Long id) throws Exception {
        return Result.judge(deviceConfigService.cancelSubscription(id));
    }
}
